import styled from '@emotion/styled'
import { Spin } from 'antd'
import { Drag, Drop, DropChild } from 'components/drag-and-drop'
import { ScreenContainer } from 'components/lib'
import React, { useCallback } from 'react'
import { DragDropContext, DropResult } from 'react-beautiful-dnd'
import { useDocumentTitle } from 'utils'
import { useKanbans, useReorderKanban } from 'utils/kanban'
import { useReorderTask, useTasks } from 'utils/task'
import { CreateKanban } from './create-kanban'
import { KanbanColumn } from './kanban-column'
import { useKanbanSearchParams, useKanbansQueryKey, useProjectInUrl, useTasksQueryKey, useTasksSearchParams } from './kanbanutils'
import { SearchPanel } from './search-panel'
import { TaskModal } from './task-modal'

export default function Kanban() {
  useDocumentTitle('看板列表')
  const { data: currentProject } = useProjectInUrl()

  const { data: kanbans, isLoading: kanbanIsLoading } = useKanbans(useKanbanSearchParams())
  // const{data: kanbans,isLoading:kanbanIsLoading} = useKanbans()
  // console.log(kanbans);

  // 加载状态
  const { isLoading: taskIsLoading } = useTasks(useTasksSearchParams())
  const isLoading = kanbanIsLoading || taskIsLoading

  const onDragEnd = useDragEnd()
  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <ScreenContainer>
        <h1>{currentProject?.name}看板</h1>
        <SearchPanel />
        {
          isLoading ? 
          <Spin size='large'></Spin> :
          <ColumnsCantainer>
            <Drop type='DOLUMN' direction='horizontal' droppableId='kanban'>
              <DropChild style={{ display: "flex" }} >
                {kanbans?.map((kanban, index) => (
                  <Drag
                    key={kanban.id}
                    draggableId={"kanban" + kanban.id}
                    index={index}
                  >
                    <KanbanColumn kanban={kanban} key={kanban.id} />
                  </Drag>
                ))}
              </DropChild>
            </Drop>
            <CreateKanban />
          </ColumnsCantainer>
        }
        <TaskModal />
      </ScreenContainer>
    </DragDropContext>
  )
}


export const useDragEnd = () => {
  const { data: kanbans } = useKanbans(useKanbanSearchParams());
  const { mutate: reorderKanban } = useReorderKanban(useKanbansQueryKey());
  const { mutate: reorderTask } = useReorderTask(useTasksQueryKey());
  const { data: allTasks = [] } = useTasks(useTasksSearchParams());
 
  return useCallback(
    ({ source, destination, type }: DropResult) => {
      // 没有排序
      if (!destination) {
        return;
      }
      // 看板排序
      if (type === "COLUMN") {
        // 看板ID
        const fromId = kanbans?.[source.index].id;
        const toId = kanbans?.[destination.index].id;
        if (!fromId || !toId || fromId === toId) {
          return;
        }
        const type = destination.index > source.index ? "after" : "before";
        reorderKanban({ fromId, referenceId: toId, type });
      }


      if (type === "ROW") {
        // = + 将string转变为number
        const fromKanbanId = +source.droppableId;
        const toKanbanId = +destination.droppableId;

        const fromTask = allTasks.filter(
          (task) => task.kanbanId === fromKanbanId
        )[source.index];

        const toTask = allTasks.filter((task) => task.kanbanId === toKanbanId)[
          destination.index
        ];

        if (fromTask?.id === toTask?.id) {
          return;
        }

        reorderTask({
          fromId: fromTask?.id,
          referenceId: toTask?.id,
          fromKanbanId,
          toKanbanId,
          type:
            fromKanbanId === toKanbanId && destination.index > source.index
              ? "after"
              : "before",
        });
      }
    },
    [kanbans, reorderKanban, allTasks, reorderTask]
  );
};




export const ColumnsCantainer = styled("div")`
  display: flex;
  overflow-x: scroll;
  margin-right: 2rem;
  flex: 1;
`
